<template>
  <div id="wrapper">
    <ExtendsElSelect 
    v-bind="$attrs"
    v-on="$listeners"
    :value-key="signData.id"
    @visible-change="visibleChange"
  >
      <el-option
        v-for="(item, index) in getOptionsData"
        :key="item[signData.id]"
        :label="item[signData.label]"
        :value="signData.value ? item : item[signData.value]">
      </el-option>
      <template slot="empty" >
        <!-- 根据数据加载状态 判断空插槽的显示 数据请求中/数据请求失败 -->
        <div class="loadingData" v-if="this.store.status === 1">
          数据加载中...
        </div>
        <div class="failButton" v-if="this.store.status === 3">
          <el-button @click="retry">重新加载</el-button>
        </div>
      </template>
    </ExtendsElSelect>
  </div>
</template>

<script>
// 使用的时候记得绑定v-model 不然报错
import ExtendsElSelect from './ExtendsElSelect.vue'

// 准备1
const props = {
        id: 'id',
        label: 'label',
        value: 'value',
        disabled: 'disabled'
      }

export default {
  name: 'StoreSelectComp',
  // 数据模型转换
  props: {
    store: {
      type: Object,
      required: true
    },
    signData: {
      type: Object,
      // 这个兜底校验 是为了不传入完整的 sigData 做处理的 如果传入完整的signData 则不需要兜底校验(建议不使用 因为我没看懂)
      validator: (value) => {
        for (let key in props) {
          if (!value.hasOwnProperty(key)) {
            const val = props[key]
            if(!value.hasOwnProperty(key)){
              value[key] = val
            }
          }
          return true
        }
      },
      // default: () => ({
      //   id: 'id',
      //   label: 'label',
      //   value: 'value',
      //   disabled: 'disabled'
      // })
      // 准备2 
      default: () => {
        return props
      }
    }
  },
  components: {
    ExtendsElSelect
  },
  created(){
    if(this.store.autoLoad && this.store.loadStrategy === 'created' && this.store.status === 0){
      // this.store.loadData() 
    }
  },
  computed:{
    getOptionsData(){
      return this.store.view.data || []
    }
  },
  methods: {
    async visibleChange(val) {
      if(val && this.store){
        try {
          // 打开请求数据
          if(this.store.autoLoad && this.store.loadStrategy === 'visible' && this.store.status === 0){
            await this.store.loadData()   
          }
        } catch (error) {
          console.log(error);
        }
      } else {
        // 关闭时如果数据正在请求 就取消请求
        if(this.store.view.status === 1){
          this.store.abort()
        }
      }
    },
    async retry(){
      try {
        await this.store.loadData()    
      } catch (error) {
        console.log(error);
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.loadingData{
  width: 100%;
  height: 40px;
  line-height: 40px;
  text-align: center;
}
.failButton{
  width: 100%;
  height: 60px;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>